<?php
/*

  Copyright (c) 2008   by  maxim.oransky <maxim.oransky@gmail.com>,
  auhtor of  the-wheel-library  team

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

class Session {

	const LAST_ACCESS_VARNAME = 'last_access';
	const REGENERATE_ID_TIME = 600; // security -- regenerate cookie id

	private static function getLifetime() {
		return 36 * Date::DAY;
	}

	public static function init() {

		ini_set('session.use_only_cookies', 1);
		ini_set('session.cookie_lifetime', self::getLifetime());
		ini_set('session.gc_maxlifetime',  self::getLifetime());

		self::create();
	}

	public static function create() {

		//self::destroy();
		session_start();

		$currentTime = time();
		$lastAccessTime = self::get(self::LAST_ACCESS_VARNAME);

		if (($currentTime - $lastAccessTime) > self::REGENERATE_ID_TIME) {

			$hData = $_SESSION;
			session_write_close();

			$newSessionId = sha1(mt_rand() * $currentTime);
			session_id($newSessionId);

			session_start();
			$_SESSION = $hData;
		}

		self::set(self::LAST_ACCESS_VARNAME, $currentTime);
	}

	public static function get($name) {
		if (!isset($_SESSION[$name])) return '';
		return $_SESSION[$name];
	}

	public static function set($name, $value) {
		$_SESSION[$name] = $value;
	}

	public static function destroy() {
		$_SESSION = array();
		session_destroy();
	}
}

Session::init();

?>